<template>
  <div class="course-versions">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span>{{ pageTitle }}</span>
          <el-button type="primary" @click="handleCreate">新增版本</el-button>
        </div>
      </template>

      <el-form :inline="true" class="search-form">
        <el-form-item label="版本名称">
          <el-input v-model="searchForm.name" placeholder="请输入版本名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData" v-loading="loading">
        <el-table-column label="版本名称" prop="name" />
        <el-table-column label="所属系列" prop="seriesName" />
        <el-table-column label="课程数量" prop="count" width="100" />
        <el-table-column label="创建时间" prop="createdAt" width="180" />
        <el-table-column label="操作" fixed="right" width="250">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" @click="handleViewCourses(row)">查看课程</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="所属系列" prop="seriesId">
          <el-select v-model="formData.seriesId" placeholder="请选择系列">
            <el-option 
              v-for="item in seriesList" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="版本名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入版本名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 课程列表对话框 -->
    <el-dialog
      v-model="courseDialogVisible"
      :title="currentVersion ? `${currentVersion.name} - 课程列表` : '课程列表'"
      width="800px"
    >
      <el-table :data="courseList" v-loading="courseLoading">
        <el-table-column label="课程名称" prop="name" />
        <el-table-column label="课程描述" prop="description" show-overflow-tooltip />
        <el-table-column label="创建时间" prop="created_at" width="180">
          <template #default="{ row }">
            {{ new Date(row.created_at).toLocaleString() }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { courseService } from '../../services/course'
import { ElMessageBox } from 'element-plus'
import { showSuccess, showError } from '../../utils/message'

// 初始化基础数据
const router = useRouter()
const route = useRoute()
const loading = ref(false)
const tableData = ref([])
const seriesList = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const currentId = ref('')

// 路由参数相关
const seriesId = computed(() => route.params.id)
const seriesName = computed(() => route.query.seriesName || '')
const pageTitle = computed(() => {
  return seriesName.value ? `${seriesName.value} - 课程版本` : '课程版本'
})

// 表单数据
const searchForm = ref({
  seriesId: seriesId.value,
  name: ''
})

const formData = ref({
  seriesId: '',
  name: ''
})

// 加载数据方法
const loadVersionList = async () => {
  try {
    loading.value = true
    const { data } = await courseService.getVersionList(seriesId.value)
    tableData.value = data
  } catch (error) {
    showError('加载课程版本失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const loadSeriesList = async () => {
  try {
    const { data } = await courseService.getSeriesList()
    seriesList.value = data
  } catch (error) {
    showError('加载课程系列失败')
    console.error(error)
  }
}

// 监听路由参数变化
watch(seriesId, (newVal) => {
  if (newVal) {
    loadVersionList()
  }
})

const formRules = {
  seriesId: [
    { required: true, message: '请选择所属系列', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入版本名称', trigger: 'blur' }
  ]
}

const handleCreate = () => {
  dialogTitle.value = '新增版本'
  dialogVisible.value = true
  currentId.value = ''
  formData.value = {
    seriesId: searchForm.value.seriesId,
    name: ''
  }
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑版本'
  dialogVisible.value = true
  currentId.value = row.id
  formData.value = {
    seriesId: row.seriesId,
    name: row.name
  }
}

const handleSearch = () => {
  loadVersionList()
}

const handleReset = () => {
  searchForm.value = {
    seriesId: seriesId.value,
    name: ''
  }
}

// 课程列表相关
const courseDialogVisible = ref(false)
const courseLoading = ref(false)
const courseList = ref([])
const currentVersion = ref(null)

const handleViewCourses = async (row) => {
  try {
    currentVersion.value = row
    courseDialogVisible.value = true
    courseLoading.value = true
    const { data } = await courseService.getCourseList(row.id)
    courseList.value = data
  } catch (error) {
    showError('加载课程列表失败')
    console.error(error)
  } finally {
    courseLoading.value = false
  }
}

const handleSubmit = async () => {
  try {
    // TODO: 完成新增/编辑课程版本的API调用
    await loadVersionList()
    dialogVisible.value = false
    showSuccess(currentId.value ? '编辑成功' : '新增成功')
  } catch (error) {
    showError(currentId.value ? '编辑失败' : '新增失败')
    console.error(error)
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除课程版本"${row.name}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    // TODO: 完成删除课程版本的API调用
    await loadVersionList()
    showSuccess('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      showError('删除失败')
      console.error(error)
    }
  }
}

// 组件挂载
onMounted(() => {
  loadSeriesList()
  if (seriesId.value) {
    loadVersionList()
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}
</style>
